package com.felix.servlet;

import java.io.BufferedOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import com.g3net.tool.HttpUtils;
import com.g3net.tool.MD5;
import com.g3net.tool.StringUtils;
import com.g3net.type.TInteger;
import com.shop.core.DataCache;
import com.shop.util.Config;

public class DownloadImageServlet extends HttpServlet {

	private static Logger log = Logger.getLogger(DownloadImageServlet.class);

	/**
	 * 
	 */
	private static final long serialVersionUID = 8998229017684793284L;

	// @Override
	public void doGet(final HttpServletRequest request,
			final HttpServletResponse response) throws ServletException,
			IOException {
		String[] url = request.getParameterValues("url");// 得到下载图片的所有链接
		log.error("image url>>>>>>>>>>: "+url+"=="+url.length);
		
		
		java.io.OutputStream out = response.getOutputStream();
		final DataOutputStream dos2 = new DataOutputStream(
				new BufferedOutputStream(out));

		try {
			for (int i = 0; i < url.length; i++) {
				byte[] b = getImgData(url[i]);
				if (b != null) {
					dos2.writeInt(1);
					dos2.writeUTF(url[i]);
					dos2.writeInt(b.length);
					dos2.write(b);
				}
			}
			dos2.writeInt(-1);
			dos2.flush();
			out.flush();
		} catch (Exception e) {
			log.error("", e);
		} finally {
			out.close();
			dos2.close();
		}

	}

	public void doPost(final HttpServletRequest request,
			final HttpServletResponse response) throws ServletException,
			IOException {
		this.doGet(request, response);
	}

	private static byte[] getImgData(String imgurl) {
		if (!StringUtils.hasText(imgurl)) {
			return null;
		}
		TInteger code = new TInteger(0);// 响应码
		byte[] imgdata = null;
		try {
			String key = MD5.MD5generator(imgurl);// 放入cache中的key
			imgdata = (byte[]) DataCache.getObject(key);
			if (imgdata == null)// cache中没有数据，则实时获取
			{
				imgdata = HttpUtils.getBytes(imgurl, code.getValue());// 暂时直接获取，不作缓存
				// 从cache中获取数据
				if (code.getValue() > 400)// 访问出错
				{
					imgdata = null;
				}
				if (imgdata != null && imgdata.length > 0) {
					// 设置cache
					DataCache.setObject(key, imgdata, Config.CACHE_TIME_DAY);
				}
			} else {
				log.debug("key=" + key + " imgdata=" + imgdata.length + " 缓存命中");
			}

		} catch (Exception e) {
			// TODO: handle exception
			log.error("", e);
			imgdata = null;
		}
		return imgdata;
	}

}
